package com.yunxin.admin.system.api.core.customer;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.yunxin.admin.system.domain.model.user.UserMerchantRepository;
import com.yunxin.admin.system.infra.common.constant.SecurityConstants;
import com.yunxin.admin.system.infra.framework.security.util.SecurityUtils;
import com.yunxin.common.result.PageResult;
import com.yunxin.common.result.Result;
import com.yunxin.core.admin.domain.AdminTeam;
import com.yunxin.core.admin.domain.AdminUser;
import com.yunxin.core.admin.domain.AdminUserTeamShip;
import com.yunxin.core.admin.service.AdminTeamService;
import com.yunxin.core.admin.service.AdminUserService;
import com.yunxin.core.admin.service.AdminUserTeamShipService;
import com.yunxin.core.customer.domain.CustomerShipAllocation;
import com.yunxin.core.customer.dto.CustomerShipAllocationAddDto;
import com.yunxin.core.customer.dto.CustomerShipAllocationEditDto;
import com.yunxin.core.customer.dto.CustomerShipAllocationPageDto;
import com.yunxin.core.customer.service.CustomerShipAllocationService;
import com.yunxin.core.customer.vo.CustomerShipAllocationVo;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.ObjectUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Tag(name = "关系配置")
@Slf4j
@RestController
@RequestMapping("/core/v1/customer/ship")
@RequiredArgsConstructor
public class CustomerShipAllocationController {

    @Autowired
    private CustomerShipAllocationService customerShipAllocationService;

    @Autowired
    private AdminUserService adminUserService;

    @Autowired
    private AdminTeamService adminTeamService;

    @Autowired
    private AdminUserTeamShipService adminUserTeamShipService;

    private final UserMerchantRepository userMerchantRepository;


    @Operation(summary = "关系配置分页列表", security = {@SecurityRequirement(name = SecurityConstants.TOKEN_KEY)})
    @PostMapping("/page")
    public PageResult<CustomerShipAllocationVo> customerShipAllocationPage(@RequestBody CustomerShipAllocationPageDto dto)  {
        List<Integer> teamIdlist = new ArrayList<>();
        if (ObjectUtils.isEmpty(dto.getTeamId())){
            Long userId = SecurityUtils.X.getUser().getUserId();
            if (SecurityUtils.X.isBokeMerchantUser()) {
                List<Long> merchantIds = userMerchantRepository.getUserMerchantIds(userId);
                LambdaQueryWrapper<AdminTeam> teamLambdaQueryWrapper=new LambdaQueryWrapper<>();
                teamLambdaQueryWrapper.eq(AdminTeam::getMerchantId,merchantIds.get(0));
                List<AdminTeam> list = adminTeamService.list(teamLambdaQueryWrapper);
                List<Integer> teamids = list.stream().map(i -> i.getId()).toList();
                teamIdlist.addAll(teamids);
            }else if (SecurityUtils.X.isBokeTeamUser()){
                LambdaQueryWrapper<AdminUserTeamShip> queryWrapper=new LambdaQueryWrapper<>();
                queryWrapper.eq(AdminUserTeamShip::getUserMerchantId,userId);
                List<AdminUserTeamShip> list = adminUserTeamShipService.list(queryWrapper);
                List<Integer> teamids = list.stream().map(i -> i.getTeamId()).toList();
                teamIdlist.addAll(teamids);
            }
        }else {
            teamIdlist.add(dto.getTeamId());
        }
        if (teamIdlist.size()<1){
            return PageResult.success(null,0);
        }
        dto.setTeamIds(teamIdlist);
        IPage<CustomerShipAllocationVo> list = customerShipAllocationService.customerShipAllocationPage(dto);
        return PageResult.success(list.getRecords(), list.getTotal());
    }



    @Operation(summary = "新增关系配置", security = {@SecurityRequirement(name = SecurityConstants.TOKEN_KEY)})
    @PostMapping("/add")
    @PreAuthorize("@ss.hasPerm('boke:ship:add')")
    public Result<Boolean> addCustomerShipAllocation(@Validated @RequestBody CustomerShipAllocationAddDto dto)  {
        Long userId = SecurityUtils.X.getUser().getUserId();
        AdminUser one = adminUserService.getOne(new LambdaQueryWrapper<AdminUser>().eq(AdminUser::getId, userId));
        dto.setCreator(one.getNickname());
        return Result.success(customerShipAllocationService.addCustomerShipAllocation(dto));
    }


    @Operation(summary = "修改关系配置", security = {@SecurityRequirement(name = SecurityConstants.TOKEN_KEY)})
    @PostMapping("/edit")
    @PreAuthorize("@ss.hasPerm('boke:ship:edit')")
    public Result<Boolean> editCustomerShipAllocation(@Validated @RequestBody CustomerShipAllocationEditDto dto)  {
        Long userId = SecurityUtils.X.getUser().getUserId();
        AdminUser one = adminUserService.getOne(new LambdaQueryWrapper<AdminUser>().eq(AdminUser::getId, userId));
        dto.setEditor(one.getNickname());
        dto.setEditTime(new Date());
        return Result.success(customerShipAllocationService.editCustomerShipAllocation(dto));
    }


    @Operation(summary = "删除关系配置", security = {@SecurityRequirement(name = SecurityConstants.TOKEN_KEY)})
    @PostMapping("/delete")
    @PreAuthorize("@ss.hasPerm('boke:ship:delete')")
    public Result<Boolean> deleteCustomerShipAllocation(@RequestParam("id") Long id)  {
        return Result.success(customerShipAllocationService.removeById(id));
    }


//    @Operation(summary = "关系配置详情", security = {@SecurityRequirement(name = SecurityConstants.TOKEN_KEY)})
//    @GetMapping("/info")
//    public Result<CustomerShipAllocation> infoCustomerShipAllocation(@RequestParam("id") Long id)  {
//        return Result.success(customerShipAllocationService.getOne(new LambdaQueryWrapper<CustomerShipAllocation>()
//                .eq(CustomerShipAllocation::getId,id)
//                .eq(CustomerShipAllocation::getIsDel,CustomerShipAllocation.NO_DEL)));
//    }

}
